package com.fire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fire.exception.ServiceException;
import com.fire.model.dto.MachineDto;
import com.fire.model.dto.MachineQueryDto;
import com.fire.model.entity.Machine;
import com.fire.mapper.MachineMapper;
import com.fire.model.enums.MachineEnum;
import com.fire.response.ResponseCodeEnum;
import com.fire.service.IMachineService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-03-27
 */
@Service
public class MachineServiceImpl extends ServiceImpl<MachineMapper, Machine> implements IMachineService {

    /**
     * 新增机器接口
     * @param dto
     */
    @Override
    public void saveMachine(MachineDto dto) throws ServiceException {
        //查询机器编号是否存在
        if(null != baseMapper.selectOne(new QueryWrapper<Machine>().eq("machine_id",dto.getMachineId()))){
            //机器已存在异常
            throw new ServiceException(ResponseCodeEnum.MACHINE_EXITS);
        }
        Machine machine = new Machine();
        machine.setMachineId(dto.getMachineId());
        machine.setLocation(dto.getLocation());
        machine.setManufacturer(dto.getManufacturer());
        machine.setStatus(MachineEnum.getMachineDescription(dto.getStatus()));
        baseMapper.insert(machine);
    }

    /**
     * 机器数据分页查询（带编号精确查询）
     * @param pageNo
     * @param pageSize
     * @param machineId
     * @return
     * @throws ServiceException
     */
    @Override
    public Map<String, Object> queryMatchMachineId(Integer pageNo, Integer pageSize, String machineId) throws ServiceException {
        Page<Machine> pageInfo = new Page<>(pageNo, pageSize);
        String machineIdTrim = "";
        if(null != machineId){
            machineIdTrim = machineId.trim();
        }
        QueryWrapper<Machine> wrapper = new QueryWrapper<>();
        if(!StringUtils.isBlank(machineIdTrim)){
            wrapper.eq("machine_id", machineIdTrim);
        }
        wrapper.orderByDesc("create_time");
        Page<Machine> machinePage = baseMapper.selectPage(pageInfo, wrapper);
        if(null != machinePage){
            List<Machine> machineList = machinePage.getRecords();
            List<MachineQueryDto> list = new ArrayList<MachineQueryDto>();
            if(!CollectionUtils.isEmpty(machineList)){
                machineList.stream().forEach(machine -> {
                    MachineQueryDto machineQueryDto = new MachineQueryDto();

                    machineQueryDto.setCreateTime(machine.getCreateTime());
                    machineQueryDto.setId(machine.getId());
                    machineQueryDto.setManufacturer(machine.getManufacturer());
                    machineQueryDto.setLocation(machine.getLocation());
                    machineQueryDto.setMachineId(machine.getMachineId());
                    machineQueryDto.setWaitTask(machine.getWaitTask());
                    machineQueryDto.setStatus(machine.getStatus().getDescription());
                    list.add(machineQueryDto);
                });
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("data",list);
                map.put("total",machinePage.getTotal());
                return map;
            }
        }
        return null;
    }

    /**
     * 机器数据分页查询（带位置模糊查询）
     * @param pageNo
     * @param pageSize
     * @param location
     * @return
     */
    @Override
    public Map<String, Object> queryMatchLocation(Integer pageNo, Integer pageSize, String location) throws ServiceException {
        Page<Machine> pageInfo = new Page<>(pageNo, pageSize);
        String locationTrim = "";
        if(null != location){
            locationTrim = location.trim();
        }
        QueryWrapper<Machine> wrapper = new QueryWrapper<>();
        if(!StringUtils.isBlank(locationTrim)){
            wrapper.like("location", locationTrim);
        }
        wrapper.orderByDesc("create_time");
        Page<Machine> machinePage = baseMapper.selectPage(pageInfo, wrapper);
        if(null != machinePage){
            List<Machine> machineList = machinePage.getRecords();
            List<MachineQueryDto> list = new ArrayList<MachineQueryDto>();
            if(!CollectionUtils.isEmpty(machineList)){
                machineList.stream().forEach(machine -> {
                    MachineQueryDto machineQueryDto = new MachineQueryDto();

                    machineQueryDto.setCreateTime(machine.getCreateTime());
                    machineQueryDto.setId(machine.getId());
                    machineQueryDto.setManufacturer(machine.getManufacturer());
                    machineQueryDto.setLocation(machine.getLocation());
                    machineQueryDto.setMachineId(machine.getMachineId());
                    machineQueryDto.setStatus(machine.getStatus().getDescription());
                    list.add(machineQueryDto);
                });
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("data",list);
                map.put("total",machinePage.getTotal());
                return map;
            }
        }
        return null;
    }

    /**
     * 机器删除接口
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) throws ServiceException {
        //只有停用的机器可以被删除
        Machine machine = baseMapper.selectById(id);

        if(machine.getStatus().getDescription().equalsIgnoreCase(MachineEnum.ACTIVATE.getDescription())){
            //说明机器是激活状态，无法被删除
            throw new ServiceException(ResponseCodeEnum.UN_SUPPORT_DELETE);
        }

        //正常删除
        baseMapper.deleteById(id);
    }

    /**
     * 回显机器数据
     * @param id
     * @return
     * @throws ServiceException
     */
    @Override
    public MachineDto echo(Integer id) throws ServiceException {
        Machine machine = baseMapper.selectById(id);

        if(null == machine) {
            throw new ServiceException(ResponseCodeEnum.DATA_NOT_EXITS);
        }
        MachineDto dto = new MachineDto();
        dto.setId(machine.getId());
        dto.setMachineId(machine.getMachineId());
        dto.setLocation(machine.getLocation());
        dto.setManufacturer(machine.getManufacturer());
        dto.setStatus(machine.getStatus().getDescription());
        return dto;
    }

    /**
     * 修改机器接口
     * @param dto
     */
    @Override
    public void updateMachine(MachineDto dto) throws ServiceException {
        Machine machine = baseMapper.selectById(dto.getId());

        if(null == machine) {
            throw new ServiceException(ResponseCodeEnum.MACHINE_NOT_FOUND);
        }

        if(machine.getMachineId().equalsIgnoreCase(dto.getMachineId())){
            //说明未修改机器编号
            machine.setStatus(MachineEnum.getMachineDescription(dto.getStatus()));
            machine.setManufacturer(dto.getManufacturer());
            machine.setLocation(dto.getLocation());
            baseMapper.updateById(machine);
        }else{
            //说明机器编号被修改，要查询修改过的机器编号是否已存在
            Machine selectOne = baseMapper.selectOne(new QueryWrapper<Machine>().eq("machine_id", dto.getMachineId()));
            if(null != selectOne){
                throw new ServiceException(ResponseCodeEnum.MACHINE_EXITS);
            }
            //说明已修改机器编号，重新设置编号
            machine.setMachineId(dto.getMachineId());
            machine.setStatus(MachineEnum.getMachineDescription(dto.getStatus()));
            machine.setManufacturer(dto.getManufacturer());
            machine.setLocation(dto.getLocation());
            baseMapper.updateById(machine);
        }
    }
}
